<template>
  <div>
    <div class="head-wrap">
      <div class="header">
        <div @click="back()" class="back"><span class="arrow"></span></div>
        <div class="head-bd">
          兑换记录
        </div>
        <div @click="goTo()" class="message"><div class="head-btn-text">预约记录</div></div>
      </div>
    </div>
    <section class>
      <div class="screen">
        <ul class="screen-menu">
          <li
            v-for="(item, index) in slider"
            @click="go(item, index)"
            :key="index"
            :class="{ active: currentIndex == index }"
          >
            <span>{{ item.title }}</span>
          </li>
        </ul>
      </div>
      <div class="mui-active">
        <div class="d-scroll list-text" style>
          <fetchData
            v-if="isLoading"
            :loading="isLoading"
            :data="swipeData"
          ></fetchData>
          <cube-scroll
            ref="scroll"
            :options="options"
            @pulling-up="onPullingUp"
            @pulling-down="onPullingDown"
          >
            <cube-swipe>
              <div class v-for="data in swipeData" :key="data.id">
                <div @click="goDetail(data)" class="item">
                  <div class="img">
                    <div class="bdt" v-if="data.categoryKey == 'BDT_KEY'"><span>补</span></div>
                    <img v-else-if="data.pic" :src="data.pic" alt="">
                  </div>
                  <div class="right-context">
                    <div class="one">
                      {{ data.goodsName }}
                      <span class="jf">
                      {{ data.totalPoint }}
                      <span class="text">积分</span>
                    </span>
                    </div>
                    <!--                  <div class="two">{{ data.note }}</div>-->
                    <div class="two">兑换时间：{{getTime(data.createTime)}}</div>
                    <div class="three">
                      <span v-if="data.categoryKey == 'BDT_KEY'">截止使用日期：{{splitNyr(data.validTimeEnd)}}&nbsp;24:00&nbsp;前</span>
<!--                      <span v-if="data.categoryKey == 'BDT_KEY'">使用期限：截止{{ getDay(data.validTimeEnd) }}前</span>-->
                      <span v-else>有效期: {{splitNyr(data.validTimeStart)}} 至 {{splitNyr(data.validTimeEnd)}}</span>
<!--                      <span v-else>使用期限: 自兑换之日起30天内有效</span>-->
                    </div>
                    <span
                      class="zt"
                      :class="fontColor(data)"
                      v-text="statusText(data)"
                    ></span>
                  </div>
                </div>
              </div>
            </cube-swipe>
            <!-- <div
              class="text-center no-data"
              v-if="!isLoading && swipeData.length === 0"
            >
              <img src="../../../../static/images/no_data.png" alt />
              <p>暂无数据</p>
            </div>
            <onBottom v-else-if="onBottom"></onBottom> -->
            <!-- W noData -->
            <noData v-if="!isLoading && swipeData.length === 0"></noData>
            <onBottom v-else-if="onBottom"></onBottom>
            <div class="pdv-10"></div>
          </cube-scroll>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
  import tools from "@/utils/tools";
  import api from "@/common/config/api";
  import moment from "moment";
  export default {
    data() {
      return {
        isLoading: true,
        fn: tools,
        onBottom: false,
        options: {
          pullUpLoad: true,
          scrollbar: false,
          pullDownRefresh: {
            threshold: 90,
            stop: 0,
            txt: ' '
          },
        },
        objectsName: "",
        swipeData: [
          /* {
            id: "82306fce06f8aaffd1b833048c80299d",
            memberId: "10000000000001",
            createTime: "2020-09-24 17:06:19",
            memberUsername: "djhy_tc",
            memberNickname: "谭神",
            totalPoint: 1,
            status: 4,
            note: null,
            goodsId: "c0e5aadd7d5646748b8dc873a3b1de68",
            goodsName: "补答题卷",
            groupId: "hybshid",
            groupName: "红云办商户",
            validTimeStart: null,
            validTimeEnd: null,
            categoryKey: "BDT_KEY",
          }, */
        ],
        productDetail: {},
        infinite: true,
        pageIndex: 1,
        fromType: "",
        subType: "",
        title: "兑换记录",
        role: true,
        roleData: "",
        showTypes: "1",
        slider: [],
        currentIndex: "0",
        statusType:'1',
      };
    },
    beforeRouteEnter (to, from, next) {
      console.log('beforeRouteEnter',to)
      console.log('from',from)
      console.log('next',next)
      localStorage.setItem('backNameRouter', from.name);
      next(vm => {
        if (to.name === 'mallForRecordList') {
          to.meta.keepAlive = true
          vm.$store.commit('addRoute', 'mallForRecordList')
        }
        next()
      })
    },
    beforeRouteLeave(to, from, next) {
      // console.log('this.$route.cachePages',this.state.cachePages);
      console.log('to',to)
      console.log('from',from)
      console.log('next',next)
      this.$route.meta.keepAlive = to.name === 'mallOrderDetail' || to.name === 'mallAppointment' ||  to.name === 'mallAppointment'
      console.log('this.$route.meta.keepAlive',this.$route.meta.keepAlive);
      if(this.$route.meta.keepAlive) {
        this.$store.commit('addRoute','mallForRecordList')
      }else {
        this.$store.commit('removeRoute','mallForRecordList')
        this.$destroy()
      }
      next()
    },
    created() {
      console.log('aaaaaaaaaaaaaaaaaaaaaaa')
      this.slider = [
        {
          title: "待使用",
          status: 1,
        },
        {
          title: "待确认",
          status: 5,
        },
        {
          title: "已使用",
          status: 2,
        },
        {
          title: "已过期",
          status: 9,
        },
        {
          title: "全部",
          status: "",
        },
      ];
      this.getPage();
    },
    methods: {
      back(){
       let backNameRouter = localStorage.getItem('backNameRouter');
        if(backNameRouter =='personalcenter'){
          this.$router.replace({  path: "/personalcenter"});
        }else{
          this.$router.replace({  path: "/supermarketHome"});
        }
      },
      goTo() {
        this.$router.push({
          path: "/mallRevocationList",
        });
      },
      goDetail(data) {
        sessionStorage.setItem("orderInfo", JSON.stringify(data)); //订单信息
        this.mallGetOrderDetail(data); //获取订单详细信息
        this.mallGetProductInfo(data); //获取商品详细信息
      },
      // 截取年月日
      splitNyr(data) {
        let str = data ? data.substr(0, 10) : "";
        return str;
      },
      // 获取订单详细信息
      mallGetOrderDetail(data) {
        this.fetchService.mallGetOrderDetail(data.id).then((res) => {
          if (res.code == 0) {
            sessionStorage.setItem("orderDetail", JSON.stringify(res.data)); //订单信息
            //不需要预约，待使用或已使用
            /*if (
              orderDetail.yuyueRecords.length == 0 &&
              (data.status == "1" || data.status == "2" || data.status == "9")
            ) {
              this.$router.push({
                path: "/mallOrderDetail",
                query: { status: data.status },
              });
            }

            //需要预约，待使用或已使用
            if (
              orderDetail.yuyueRecords.length > 0 &&
              (data.status == "1" || data.status == "2")
            ) {
              this.$router.push({
                path: "/mallAppointment",
                query: { status: data.status },
              });
            }

            if (orderDetail.yuyueRecords.length > 0 &&
              (data.status == "4" ||
              data.status == "5" ||
              data.status == "6" ||
              data.status == "7" ||
              data.status == "9")
            ) {
              //待预约，跳转至预约页面
              this.$router.push({
                path: "/mallAppointment",
                query: { status: data.status },
              });
            }*/
          }
        });
      },
      // 获取商品详情信息
      mallGetProductInfo(data) {
        // this.fetchService.mallGetProductInfo(data.goodsId).then((res) => {
        console.log('datadata=',data);
         let params={
           orderId: data.id,
           productId: data.goodsId
         }
        this.fetchService.mallGetProductOrderInfo(params).then((res) => {
          if (res.code == 0) {
            this.productDetail = res.data;
            console.log('this.productDetail',this.productDetail);
            let status = this.productDetail.sfyy === '1' ? true : false
            // debugger
            sessionStorage.setItem("productDetail",JSON.stringify(this.productDetail)); //商品信息
            sessionStorage.setItem('commodityInfo',JSON.stringify(this.productDetail));
            //不需要预约
            if(!status){
              this.$router.push({
                path: "/mallOrderDetail",
                query: { status: data.status },
              });
            }
            //需要预约
            if(status){
              this.$router.push({
                path: "/mallAppointment",
                query: { status: data.status },
              });
            }
          }
        });
      },
      // 状态字典匹对
      statusText(data) {
        let statusName = {
          1: "待使用", // 需预约到预约页（6小时前第2步、6小时内第三步、过期第三步、）、不需预约到订单详情页
          2: "已使用", // 需预约到预约页第3步（已使用）、不需预约到订单详情页（已使用）
          4: "待预约", // 需预约到预约页第1步
          5: "待确认", // 需预约到预约页第2步，文档说到第1步
          6: "预约失败", // 需预约到预约页第1步
          7: "已撤销", // 需预约到预约页第1步
          9: "已过期",
        };
        return statusName[data.status];
      },
      // 状态颜色匹对
      fontColor(data) {
        let colorName = {
          1: "color-green",
          2: "color-tip",
          4: "color-red",
          5: "color-green",
          6: "color-tip",
          7: "color-tip",
          9: "color-tip",
        };
        return colorName[data.status];
      },
      //跳转积分区间
      go(data, index) {
        this.statusType = data.status;
        this.pageIndex = 1;
        this.currentIndex = index;
        this.swipeData = [];//
        this.getPage()
      },
      getPage() {
        this.onBottom = false;
        this.isLoading = true;
        let data = {
          pageNo: this.pageIndex + "",
          pageSize: 20,
          status: this.statusType
        };
        this.fetchService.mallOrderPage(data).then((res) => {
          this.isLoading = false;
          if (res.code !== 0) {
            this.$refs.scroll.forceUpdate && this.$refs.scroll.forceUpdate();
            return tools.tip(res.message);
          }
          if (res.code === 0 && res.data.length < 1) {
            this.options.pullUpLoad = false
            this.onBottom = true;
            this.$refs.scroll.forceUpdate && this.$refs.scroll.forceUpdate();
            return;
          }
          if(this.swipeData.length>0 && !this.isHasFocus(this.swipeData[0].id,res.data)){
            this.swipeData = this.swipeData.concat(res.data)
          }else{
            this.swipeData = res.data
          }
          this.pageIndex++;
          setTimeout(() => {
            this.$refs.scroll.forceUpdate &&
            this.$refs.scroll.forceUpdate(true, false);
          }, 100);
          this.data = res.data;
        });
      },
      onPullingUp() {
        console.log("onPullingUp");
        this.getPage();
      },
      onPullingDown() {
        this.swipeData = []
        this.options.pullUpLoad = true
        console.log('onPullingDown')
        this.pageIndex = 1
        this.getPage();
      },
      getTime (createTime) {
        return moment(createTime).format('YYYY-MM-DD日 HH:mm:ss')
      },
      /*判断是否存在某个值*/
      isHasFocus (userId, list) {
        let ret = false
        list.some(v => {
          if (v.id === userId) {
            ret = true
            return false
          }
        })
        return ret
      },
      /*getDay(createTime){
        return moment(createTime).format("yyyy年MM月DD日")+"24:00"
      },*/
    },
  };
</script>

<style scoped lang="scss">
  @import "@/common/stylus/moon.scss";
  .d-scroll {
    height: calc(100vh - 2.4rem - .66667rem);
  }
  .list-text .item {
    font-size: $titleFontSize;
    padding: .4rem;
    border-bottom: 1px solid #d0d0d0;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    background: #fff;
    .img{
      margin-right: 0.3rem;
      /*float: left;*/
      position: relative;
      overflow: hidden;
      width: 2.4rem;
      height: 2.4rem;
      background: none;
      border-radius: 0.13333rem;
      -ms-flex-negative: 0;
      flex-shrink: 0;
      background: #f6f6f6;
      >img{
        position: relative;
        overflow: hidden;
        width: 2.4rem;
        border-radius: 0.13333rem;
        -ms-flex-negative: 0;
        flex-shrink: 0;
      }
      .bdt{
        background: #ffb800;
        width: 100%;
        height: 100%;
        text-align: center;
        >span{
          color:#ffffff;
          font-size: 1.5rem;
          text-align: center;
          line-height: 12vh;
        }
      }
    }
    .right-context{
      width: 80%;
      .one {
        font-weight: bolder;
        padding-bottom: 10px;
        .jf {
          font-weight: bold;
          font-size: inherit;
          color: #e20002;
          float: right;
          .text {
            font-size: $tipFontSize;
            color: #9a9a9a;
          }
        }
      }
      .two {
        font-size: $tipFontSize;
        color: #9a9a9a;
      }
      .three {
        font-size: 14PX;
        color: #e20002;
        width: 60%;
        float: left;
        margin-top: 3%;
        >span{
          width:100%;
        }
      }
      .zt {
        font-weight: inherit;
        font-size: inherit;
        color: #2aab0e;
        line-height: 18px;
        padding: 10px 15px;
        border: 1px solid #2aab0e;
        border-radius: 10px;
        float: right;
        /* position: relative;
        top: -8px; */
        cursor: pointer;
        margin-top: 5%;
      }
      span {
        font-weight: inherit;
        font-size: inherit;
      }
    }
  }
  .color-green {
    border: 1px solid #16bb00 !important;
  }
  .color-tip {
    border: 1px solid #999 !important;
  }
  .color-red {
    border: 1px solid $theme-color !important;
  }
  .screen {
    width: 100%;
    height: 108px;
    background: #fff;
    margin-top: 2%;
    margin-bottom: 2%;
    .screen-menu {
      height: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px;
      li {
        font-size: 14PX;
        padding: 6px 10px;
        border: 1px solid #e5e5e5;
        border-radius: 10px;
        &.active {
          border: 1px solid #e20002;
          font-weight: bold;
          color: #e20002;
        }
      }
    }
  }
</style>
